import fetch from 'dva/fetch';
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function checkData(data) {
  if (data.status != 503) {
    return;
  } else {
    document.location = './#/login';
  }
  const error = new Error(data.msg);
  throw error;
}
/**
 * author renzhiqiang
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export  async function request(url,type,options) {
  let defaultOptions = {method: 'GET', mode: 'no-cors', credentials:'include'};
  try {
    switch (arguments.length){
      case 0:{ // 0个参数
        console.error('请输入参数!!!!');
        return;
      }
      case 1:{ // 1个参数
        if(typeof url != "string"){
          console.error('url请输入字符串!!!!');
          return;
        }
        break;
      }
      case 2:{ // 2个参数
        if(typeof type == "object"){
          Object.assign(defaultOptions,type)
        } else {
          if(type.toLocaleUpperCase()=="POST"){
            defaultOptions.method="POST";
            defaultOptions.headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
          }
        }
        break;
      }
      case 3:{
        if(type.toLocaleUpperCase()=="POST"){
          defaultOptions.method="POST";
          defaultOptions.headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        }
        Object.assign(defaultOptions,options);
        break;
      }
      default:{
        console.error('数据参数格式有问题,请修改!!!')
      }
    }
    const response = await fetch(url, defaultOptions);
    checkStatus(response);
    const data = await response.json();
    checkData(data);
    return data;
  } catch (e){
    console.info(e);
  }
}
/**
 * Requests a URL, returning a promise.(静态数据测试专用接口)
 *
 * @param  {string} url       The URL we want to request
 * @return {object}           An object containing either "data" or "err"
 */

export async function requestTest(url) {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}
